package com.yjt.javatest.service.impl;

import com.alibaba.fastjson2.JSONObject;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.yjt.javatest.dao.CategoryMapper;
import com.yjt.javatest.dao.QuestionMapper;
import com.yjt.javatest.entity.CategorizedQuestion;
import com.yjt.javatest.entity.Category;
import com.yjt.javatest.entity.Question;
import com.yjt.javatest.service.CategoryService;
import com.yjt.javatest.utils.APIResponse;
import com.yjt.javatest.utils.SecurityUtil;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import javax.annotation.Resource;
import java.util.*;
import java.util.concurrent.locks.Lock;
import java.util.concurrent.locks.ReentrantLock;


@Service("categoryService")
public class CategoryServiceImpl extends ServiceImpl<CategoryMapper, Category> implements CategoryService {

    @Resource
    private CategoryMapper categoryMapper;
    @Resource
    private QuestionMapper questionMapper;
    private final Lock lock = new ReentrantLock();
    @Override
    @Transactional(rollbackFor = Exception.class)
    public APIResponse createCategory(Category category) {
        synchronized (SecurityUtil.getUserId()) {
            if (Objects.isNull(category.getFatherId())) {
                return APIResponse.error("父id不能为空");
            }
            if (Objects.isNull(category.getName())) {
                return APIResponse.error("分类名不能为空!");
            }
            if(Objects.isNull(categoryMapper.selectById(category.getFatherId()))) {
                return APIResponse.error("父分类不存在");
            }
            category.setUserId(SecurityUtil.getUserId());
            category.setId(null);
            int result = categoryMapper.insert(category);
            if (result > 0) {
                return APIResponse.success("新建分类成功");
            }
            return APIResponse.error("新建分类失败");
        }
    }

    @Override
    public APIResponse listCategoriesByFatherId(Integer fatherId) {
        if(Objects.isNull(fatherId)) {
            return APIResponse.error("父id为空");
        }
        QueryWrapper<Category> wrapper = new QueryWrapper<>();
        wrapper.eq("father_id",fatherId)
                .eq("user_id", SecurityUtil.getUserId());
        List<Category> categories = categoryMapper.selectList(wrapper);
        return APIResponse.success(categories);
    }

    /**
     * 递归删除
     */
    @Transactional(rollbackFor = Exception.class)
     void recursiveDelete(Integer fatherId, Integer id) {
        //获取父id为id的所有分类
        QueryWrapper<Category> wrapper = new QueryWrapper<>();
        wrapper.eq("father_id",id);
        List<Category> categories = categoryMapper.selectList(wrapper);
        if(!Objects.isNull(categories) && !categories.isEmpty()) {
            for (Category category : categories) {
                //把分类id为id的题目的分类id改为rootId
                questionMapper.updateCategoryIdByCategoryId(fatherId, id, SecurityUtil.getUserId());
                recursiveDelete(fatherId, category.getId());
            }
        }
        //删除所有父id为id的分类
         categoryMapper.delete(wrapper);
    }
    @Override
    @Transactional(rollbackFor = Exception.class)
    public synchronized APIResponse deleteCategoryById(Integer id) {
            try {
                Category category = categoryMapper.selectById(id);
                if (Objects.isNull(category)) {
                    return APIResponse.error("该分类不存在");
                }
                if (category.getFatherId().equals(0)) {
                    return APIResponse.error("不能删除根节点");
                }
                recursiveDelete(category.getFatherId(), id);
                categoryMapper.deleteById(id);
            } catch (Exception e) {
                return APIResponse.error("删除失败");
            }
        return APIResponse.success("删除成功");
    }

    @Override
    public APIResponse listAll() {
        Long userId = SecurityUtil.getUserId();
        QueryWrapper<Category> wrapper = new QueryWrapper<>();
        wrapper .eq("user_id", userId);
        List<Category> categories = categoryMapper.selectList(wrapper);
        HashMap<Integer, CategorizedQuestion> questionMap = new HashMap<>();
        //创建并设置每个分类的题目
        for (Category category : categories) {
            CategorizedQuestion categorizedQuestion = new CategorizedQuestion(category);
            List<Question> questions = questionMapper.getQuestionsByCategoryIdWithoutImage(category.getId(), userId);
                for (Question question : questions) {
                    String content = (String) JSONObject.parse(question.getContent()).get("content");
                    try {
                        content = content.substring(0, Math.min(20,content.length()));
                    } catch (Exception e) {
                        e.printStackTrace();
                        return APIResponse.error(String.format("id:%d,有问题,请检查题目格式", question.getQuestionId()));
                    }
                    if (content.length() == 20) {
                        content = content + "...";
                    }
                    question.setContent(content);
                }
            categorizedQuestion.setQuestions(questions);
            questionMap.put(category.getId(), categorizedQuestion);
        }
        //设置每个分类的子分类
        CategorizedQuestion root = null ;
        for (Map.Entry<Integer, CategorizedQuestion> entry : questionMap.entrySet()) {
            if(entry.getValue().getFatherId() != 0) {
                questionMap.get(entry.getValue().getFatherId()).getChildren().add(entry.getValue());
            } else {
                root = entry.getValue();
            }
        }
        if(Objects.isNull(root)) {
            return APIResponse.error("没有分类");
        }
        return APIResponse.success(root);
    }
}

